import 'package:casdon/common/service/tuya_service.dart';
import 'package:casdon/core/logger/log.dart';
import 'package:casdon/core/utils/toast_utils.dart';
import 'package:casdon/modules/recipe/application/notification/recipe_products_notifier.dart';
import 'package:casdon/modules/recipe/data/model/recipe_ecoprotocol_model.dart';
import 'package:casdon/modules/recipe/domain/states/recipe_dispatch_state.dart';
import 'package:casdon/modules/recipe/domain/usecase/recipe_ecprotocol_usecase.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:tuya_home_sdk_flutter/tuya_home_sdk_flutter.dart';

//  下发菜谱
class RecipeDispatchNotifier
    extends AutoDisposeAsyncNotifier<RecipeDispatchState> {
  @override
  Future<RecipeDispatchState> build() async {
    return RecipeDispatchState.initial();
  }

  Future<void> fetchData({
    required String recipeId,
    required String? devId,
  }) async {
    try {
      state = AsyncLoading();

      // 获取可用设备列表
      final canUseProductState = ref.read(
        recipeCanUseProductsProvider(recipeId),
      );
      if (canUseProductState.devList.isEmpty) return;

      List<ThingSmartDeviceModel> canUseDevList = [];

      if (devId != null) // 从菜谱智能页面进来，有pid值
      {
        final devList = await TuyaService().homeDeviceList();
        final ThingSmartDeviceModel targetDevice = devList.firstWhere(
          (e) => e.devId == devId,
        );
        canUseDevList = [targetDevice];
      } else {
        final matches = canUseProductState.devList
            .where((item) => item.devId == devId)
            .toList();

        ThingSmartDeviceModel? target = matches.isNotEmpty
            ? matches.first
            : null;
        if (target == null) {
          return;
        }
        // 智能页面进来，默认选中pid对应的设备
        canUseProductState.devList.remove(target);
        canUseProductState.devList.insert(0, target);
        canUseDevList = canUseProductState.devList;
      }

      final ThingSmartDeviceModel targetDevice = canUseDevList.first;
      final String? targetCiotPid =
          canUseProductState.pidMap[targetDevice.productId];
      if (targetCiotPid == null) return;
      // 获取电控协议（参数pid：需要传递涂鸦pid对应的ciot pid）
      final ecoRet = await ref
          .read(recipeEcprotocolUsecaseProvider)
          .execute(recipeId: recipeId, pid: targetCiotPid);

      RecipeEcoprotocolModel? ecoModel = RecipeEcoprotocolModel.fromApi(
        ecoRet,
        targetDevice,
      );

      if (ecoModel == null) {
        Log.i("电控协议接口，烹饪参数为空");
      }

      RecipeDispatchState newState = RecipeDispatchState(
        ecoModel: ecoModel,
        devList: canUseDevList,
        devIndex: 0,
        recipeId: recipeId,
      );
      state = AsyncData(newState);
    } catch (e, st) {
      state = AsyncError(e, st);
      ToastUtil.show("获取数据失败");
      Log.e("RecipeDispatchNotifier fetchData failed", e.toString(), st);
    }
  }

  // 下发菜谱
  Future<bool> dispatch() async {
    if (state.value == null) return false;
    if (!_checkCanDispatch()) return false;

    Map<String, dynamic>? dps = state.value!.ecoModel?.dps;
    if (dps == null) return false;

    final recipeProduct = state.value!.devList?[state.value!.devIndex ?? 0];
    if (recipeProduct == null) return false;
    final String devId = state.value!.devList!.first.devId!;
    final ret = await TuyaService().publishDps(deviceId: devId, dps: dps);

    if (ret == false) {
      ToastUtil.show("菜谱下发失败");
      Log.i("菜谱下发失败  = $devId: $dps");
    } else {
      ToastUtil.show("菜谱下发成功");
      Log.i("菜谱下发成功  = $devId: $dps");
    }
    return ret;
  }

  /** 
 *  cook_status
 * reservation预约中 
 * cooking烹饪中 
 * cancel烹饪取消 
 * wait烹饪等待 
 * done烹饪完成 
 * pause烹饪暂停 
 * preheating预热，
 * preheat_warming预热完成保温中（APP上取消时，APP下发cancel或wait）
 * standby待机中
 */
  bool _checkCanDispatch() {
    if (state.value == null) {
      return false;
    }
    if (state.value!.devList == null || state.value!.devList!.isEmpty) {
      return false;
    }
    final ThingSmartDeviceModel model =
        state.value!.devList![state.value!.devIndex ?? 0];

    if (!model.isOnline) {
      ToastUtil.show("产品已离线，启动失败！");
      return false;
    }
    int statusDpCode = -1;
    for (ThingSmartSchemaModel schema in model.schemaArr ?? []) {
      if (schema.code == "cook_status") {
        statusDpCode = schema.id;
      }
    }
    if (statusDpCode == -1) {
      return false;
    }
    Map? dps = model.dps;
    if (dps == null) return false;
    if (dps.containsKey(statusDpCode.toString()) == false) return false;
    String dpValue = dps[statusDpCode.toString()];
    if (dpValue == "wait" ||
        dpValue == "done" ||
        dpValue == "cancel" ||
        dpValue == "standby") {
      return true;
    }
    ToastUtil.show("请先取消当前工作！");
    return false;
  }

  void updateSelectedIndex(int value) {
    if (state.value == null) {
      return;
    }
    if (state.value!.devList == null || state.value!.devList!.isEmpty) {
      return;
    }
    if (value >= state.value!.devList!.length) {
      return;
    }
    RecipeDispatchState stateData = state.value!;
    stateData = stateData.copyWith(devIndex: value);
    state = AsyncData(stateData);
  }
}

final recipeDispatchNotifierProvider =
    AsyncNotifierProvider.autoDispose<
      RecipeDispatchNotifier,
      RecipeDispatchState
    >(RecipeDispatchNotifier.new);
